﻿using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ITViet.Web.App_Code;
using System.Data;
using ITViet.Services;

namespace ITViet.Web.Controls
{
  public partial class AdminSubMenu : AdminBaseControl
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
        ShowMenu();
      }
      if (Page.IsPostBack)
      {
        if (Request["__EVENTTARGET"] == "AdminLeftMenuChange")
        {
          string[] paras = Request["__EVENTARGUMENT"].Split('|');
          if (paras.Length >= 2)
          {
            SelectedSubMenuItem = paras[0];
            Response.Redirect(paras[1]);
          }
        }
      }
    }

    protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
      string path = Request.Url.AbsolutePath;
      string currentPage = path.Substring(path.LastIndexOf('/') + 1);
      if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
      {
        currentPage += "?" + Request.QueryString;
      }

      DataRowView element = (DataRowView)e.Item.DataItem;
      HtmlControl lnkMenuItem = e.Item.FindControl("lnkMenuItem") as HtmlControl;

      if (lnkMenuItem != null)
      {
        lnkMenuItem.Attributes.Add("onclick", string.Format("javascript:getCurrentElement('{0}','{1}')"
                                      , element["Id"] != null ? element["Id"].ToString() : string.Empty
                                      , element["Link"] != null ? element["Link"].ToString() : string.Empty));
        //lnkMenuItem.Attributes["href"] = "~/Admin/" + lnkMenuItem.Attributes["href"];

        if (!string.IsNullOrEmpty(SelectedSubMenuItem) &&
          element["Id"] != null && element["Id"].ToString().Trim() == SelectedSubMenuItem.Trim())
        {
          lnkMenuItem.Attributes["class"] = "active";
          SelectedSubMenuItemTitle = element["Title"].ToString();
        }
        else if (element["Link"] != null && element["Link"].ToString().Trim() == currentPage.Trim())
        {
          lnkMenuItem.Attributes["class"] = "active";
          SelectedSubMenuItem = element["Id"].ToString();
          SelectedSubMenuItemTitle = element["Title"].ToString();
        }
      }
    }

    private void ShowMenu()
    {
      if (string.IsNullOrEmpty(SelectedMenuItem)) SelectedMenuItem = "0";
      DataSet ds = new SubMenuService().GetSubMenuByLanguage(Convert.ToInt32(SelectedMenuItem), CurrentLanguage.Id, CurrentUser.Username);
      if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
      {
        SelectedSubMenuItemTitle = SelectedMenuItemTitle;
      }
      rptMenu.DataSource = ds;
      rptMenu.DataBind();
    }
  }
}